package com.common;

import com.entity.Manager;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebContextHelper {

    private static final String CURRENT_ONLINE_USER = "ONLINE.USER";

    /**
     * 获取HttpServletRequest对象
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }

    /**
     * 获取HttpServletResponse对象
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getResponse();
    }

    /**
     * 获取HttpSession
     *
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession(true);
    }

    /**
     * 获取HttpSession
     *
     * @param b
     * @return
     */
    public static HttpSession getSession(boolean b) {
        return getRequest().getSession(b);
    }

    /**
     * 将当前登录用户设置到session中
     *
     * @param manager
     * @return
     */
    public static boolean setOnLineUser(Manager manager) {
        HttpSession session = getSession(true);
        session.setAttribute(CURRENT_ONLINE_USER, manager);
        return true;
    }

    /**
     * 从session中清除当前登录用户
     *
     * @return
     */
    public static boolean removeOnLineUser() {
        HttpSession session = getSession(true);
        session.removeAttribute(CURRENT_ONLINE_USER);
        return true;
    }

    /**
     * 从session中取出当前登录用户，如果没有登录用户则返回null
     *
     * @return
     */
    public static Manager getOnLineUser() {
        HttpSession session = getSession(true);
        return (Manager) session.getAttribute(CURRENT_ONLINE_USER);
    }

    public static void invalidateSession() {
        HttpSession session = getSession(false);
        if (null != session) {
            session.invalidate();
        }
    }

}